#include "gotopageinput.h"

#include <QStyleOption>
#include <QRegularExpressionValidator>
#include <QRegularExpression>

#include <QPainter>

#include "../../uitools/vhc/constview4fun.h"
#include "../../uitools/vhc/constview4id.h"


namespace kepen {
namespace core {

GotoPageInput::GotoPageInput(QWidget *parent) : QWidget(parent)
{

    QString nameThiz("goto_page_item");
    QString cssThiz = QString("QWidget#%1{background-color:transparent;font-size:%2px;}").arg(nameThiz).arg(TextSize_ToolBar);
    // QString cssLabel = QString("QLabel{font-family:Microsoft Yahei;font-size:%1px;}").arg(TextSize_ToolBar);
    QString cssInput = QCSS_Input();
    setObjectName(nameThiz);
    setStyleSheet(cssThiz);
    m_pHMainLayout = new QHBoxLayout(this);
    // m_pLabel1 = new QLabel("前往", this);
    QLineEdit * _input= new QLineEdit(this);
    // m_pLabel2 = new QLabel("页 共0页", this);
    // m_pLabel1->setStyleSheet(cssLabel);
    _input->setStyleSheet(cssInput);
    // m_pLabel2->setStyleSheet(cssLabel);
    // m_pLabel1->adjustSize();
    // m_pLabel2->adjustSize();
    _input->setFixedSize(50, 30);
    QRegularExpression reg("[0-9]+$");
    QRegularExpressionValidator* va = new QRegularExpressionValidator(reg, _input);
    _input->setValidator(va);
    // m_pHMainLayout->addWidget(m_pLabel1);
    m_pHMainLayout->addWidget(_input,0,Qt::AlignLeft);
    // m_pHMainLayout->addWidget(m_pLabel2);
    //m_pHMainLayout->addStretch();

    m_pHMainLayout->setContentsMargins(0, 0, 0, 0);
    m_pHMainLayout->setSpacing(0);
    setContentsMargins(0, 0, 0, 0);

    _input->installEventFilter(this);

    m_pInput = _input;
}

GotoPageInput::~GotoPageInput()
{

}

void GotoPageInput::setCurrentPage(int indexPage)
{
    QString text = QString::number(indexPage,10);

    m_pInput->setText(text);
    // m_pLabel2->setText(textTotal);
    // m_pLabel2->adjustSize();
}

void GotoPageInput::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    QWidget::paintEvent(event);
}

bool GotoPageInput::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QKeyEvent::KeyRelease)
    {
        Qt::Key k = static_cast<Qt::Key>((dynamic_cast<QKeyEvent*>(event)->key()));

        if(k == Qt::Key_Return || k == Qt::Key_Enter)
        {
            int nPage = 1;
            QString str = m_pInput->text();

            if(str.isEmpty()|| str.isNull()){
                m_pInput->setText("1");
            }else
                nPage = str.toInt();

            emit GotoPage(nPage);
            return true;
        }
    }
    return QWidget::eventFilter(watched, event);
}


}
}
